package ru.hh.team02.chat.client;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

/*
	При запуске можно задавать порт для внутреннего общения, если не задан - по умолчанию(4444).
 */

public class ClientWriter implements Runnable {
	private final static int CLIENT_PORT = 5555;
	
	private int clientPort;
	private Socket socket;
	private ObjectOutputStream outputStream;

	public static void main(String[] args) {
		int clientPort;
		if (args.length == 0) {
			clientPort = CLIENT_PORT;
		} else {
			clientPort = Integer.parseInt(args[0]);
		}
		new ClientWriter(clientPort).run();
	}
	
	public ClientWriter(int clientPort) {
		this.clientPort = clientPort;
	}
	
	private void connect() throws Exception {
		socket = new Socket("localhost", clientPort);
		outputStream = new ObjectOutputStream(socket.getOutputStream());
	}
	

	@Override
	public void run() {
		try {
			connect();
			Scanner scanner = new Scanner(System.in);
			while (true) {
				String input = scanner.nextLine();
				outputStream.writeObject(input);
				if (input.equals("exit")) {
					socket.close();
					System.exit(0);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
